package com.aldobucchi.mouse
{
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.geom.Point;
	
	import com.aldobucchi.utils.App;
	import com.aldobucchi.x.flash.geom.PolarPoint;
	import com.aldobucchi.x.flash.geom.Segment;
	
	public class MouseDragInertia
	{
		

		private var target:DisplayObject;
		
		private var points:Array;


		private var speed:PolarPoint;
		

		internal var isPlaying:Boolean;

		
		public function MouseDragInertia( target:DisplayObject )
		{
	
			this.target 	= target;
			this.points 	= new Array( );

		}

		
		internal function start( ):void
		{
			speed = processPoints( );
			App.app.addEventListener( Event.ENTER_FRAME, onEnterFrame, false, 0, true );
		}

		
		internal function stop( ):void
		{
			App.app.removeEventListener( Event.ENTER_FRAME, onEnterFrame, false );
		}
		
		
		internal function logPoint( point:Point ):void
		{
			points.push( point );
		}
		
		
		
		
		private function onEnterFrame( event:Event ):void
		{
		
			if ( speed.len <= 0 )
			{
				stop( );
				return;
			}
			
			
			// move

			try 			
			{
				target.x += speed.x;
				target.y += speed.y;
			
			} catch ( e:Error ){}
						
			
			// decay
			speed = new PolarPoint( speed.len - 10, speed.angle );
		
		}
		
		
		
		
		
	
		private function processPoints( ):PolarPoint
		{
		
			// use the last two points for now
			if ( points.length < 2 )
				return new PolarPoint( 0, 0 );
			
			var seg:Segment = new Segment(  points[ points.length - 2 ], points[ points.length -1 ] );			
			
			return PolarPoint.fromPoint( seg.fromOrigin.pointB );
			
					
		
		}		
		

	}
}